#include "LinkedQueue.h"

LinkedQueue* init_queue() {
    LinkedQueue* queue = (LinkedQueue*)malloc(sizeof(LinkedQueue));
    queue->front = NULL;
    queue->rear = NULL;
}

Node* create_node(ElemType data) {
    Node* new_node = (Node*)malloc(sizeof(Node));
    new_node->data = data;
    new_node->next = NULL;
    return new_node;
}

int is_empty(LinkedQueue* queue) { return queue->front == NULL; }

int size(LinkedQueue* queue) {
    int cnt = 0;
    // while (queue->front != NULL) {
    //     queue->front = queue->front->next;
    //     cnt++;
    // }
    for (Node* cur = queue->front; cur != NULL; cur = cur->next, cnt++);
    return cnt;
}

void enqueue(LinkedQueue* queue, ElemType data) {
    Node* new_node = create_node(data);
    if (is_empty(queue)) {
        queue->front = new_node;
        queue->rear = new_node;
    } else {
        queue->rear->next = new_node;
        queue->rear = new_node;
    }
}

ElemType dequeue(LinkedQueue* queue) {
    if (is_empty(queue)) {
        printf("dequeue: Queue is empty.\n");
        return -1;
    }
    Node* temp = queue->front;
    ElemType data = temp->data;
    queue->front = queue->front->next;
    if (queue->front == NULL) {
        queue->rear = NULL;
    }
    free(temp);
    return data;
}

ElemType front(LinkedQueue* queue) {
    if (is_empty(queue)) {
        printf("front: Queue is empty.\n");
        return -1;
    }
    return queue->front->data;
}

void dequeue_all(LinkedQueue* queue) {
    printf("[Front << ");
    while (!is_empty(queue)) {
        printf("%d << ", dequeue(queue));
    }
    printf("Rear]\n");
}

void clear_queue(LinkedQueue* queue) {
    while (!is_empty(queue)) {
        dequeue(queue);
    }
    free(queue);
    // 记得在调用clear_queue后将指针置为NULL，避免野指针
}